from rest_framework.response import Response
from rest_framework import status
from rest_framework.views import exception_handler
import logging

logger = logging.getLogger(__name__)

class APIResponse:
    """统一API响应格式"""
    
    @staticmethod
    def success(data=None, message="操作成功", code=200):
        """成功响应"""
        return Response({
            'success': True,
            'code': code,
            'message': message,
            'data': data
        }, status=status.HTTP_200_OK)
    
    @staticmethod
    def error(message="操作失败", code=400, data=None, http_status=None):
        """错误响应"""
        if http_status is None:
            if code == 401:
                http_status = status.HTTP_401_UNAUTHORIZED
            elif code == 403:
                http_status = status.HTTP_403_FORBIDDEN
            elif code == 404:
                http_status = status.HTTP_404_NOT_FOUND
            elif code >= 500:
                http_status = status.HTTP_500_INTERNAL_SERVER_ERROR
            else:
                http_status = status.HTTP_400_BAD_REQUEST
        
        return Response({
            'success': False,
            'code': code,
            'message': message,
            'data': data
        }, status=http_status)
    
    @staticmethod
    def paginated_success(data, message="获取成功", code=200):
        """分页成功响应"""
        return Response({
            'success': True,
            'code': code,
            'message': message,
            'data': {
                'results': data.get('results', []),
                'count': data.get('count', 0),
                'next': data.get('next'),
                'previous': data.get('previous'),
                'page_size': data.get('page_size', 20),
                'current_page': data.get('current_page', 1),
                'total_pages': data.get('total_pages', 1)
            }
        }, status=status.HTTP_200_OK)

def custom_exception_handler(exc, context):
    """自定义异常处理器"""
    # 调用DRF默认的异常处理器
    response = exception_handler(exc, context)
    
    if response is not None:
        # 记录异常日志
        logger.error(f"API异常: {exc}", exc_info=True)
        
        # 自定义错误响应格式
        custom_response_data = {
            'success': False,
            'code': response.status_code,
            'message': '请求处理失败',
            'data': None
        }
        
        # 处理不同类型的异常
        if hasattr(exc, 'detail'):
            if isinstance(exc.detail, dict):
                # 字段验证错误
                errors = []
                for field, messages in exc.detail.items():
                    if isinstance(messages, list):
                        for message in messages:
                            errors.append(f"{field}: {message}")
                    else:
                        errors.append(f"{field}: {messages}")
                custom_response_data['message'] = '; '.join(errors)
            elif isinstance(exc.detail, list):
                custom_response_data['message'] = '; '.join(str(msg) for msg in exc.detail)
            else:
                custom_response_data['message'] = str(exc.detail)
        
        # 特殊状态码处理
        if response.status_code == 401:
            custom_response_data['message'] = '未授权访问，请先登录'
        elif response.status_code == 403:
            custom_response_data['message'] = '权限不足'
        elif response.status_code == 404:
            custom_response_data['message'] = '请求的资源不存在'
        elif response.status_code == 405:
            custom_response_data['message'] = '请求方法不允许'
        elif response.status_code >= 500:
            custom_response_data['message'] = '服务器内部错误'
        
        response.data = custom_response_data
    
    return response